package com.jwiki.app.jkeeper.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jwiki.app.jkeeper.common.jdbc.JdbcUtils;
import com.jwiki.app.jkeeper.common.jdbc.Page;
import com.jwiki.app.jkeeper.controller.form.CategoryForm;
import com.jwiki.app.jkeeper.repository.bean.CategoryBean;
import com.jwiki.app.jkeeper.repository.bean.SubCategoryBean;
import com.jwiki.app.jkeeper.repository.mapper.CategoryMapper;
import com.jwiki.app.jkeeper.repository.model.CategoryModel;
import com.jwiki.app.jkeeper.service.BaseService;
import com.jwiki.app.jkeeper.service.CategoryService;

@Service
public class CategoryServiceImpl extends BaseService implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryBean> getCategory(CategoryForm form) {
        CategoryModel model = new CategoryModel();
        BeanUtils.copyProperties(form, model);
        return categoryMapper.selectCategory(model);
    }

    @Override
    public Page<CategoryBean> getCategoryByPage(CategoryForm form) {
        Page<CategoryBean> page = JdbcUtils.build().orderBy(form.getOrderBy())
                .limit(form.getOffset(), form.getLimit()).getPage();
        CategoryModel model = new CategoryModel();
        BeanUtils.copyProperties(form, model);
        page.setData(categoryMapper.selectCategory(model));
        return page;
    }

    @Transactional
    @Override
    public boolean saveCategory(CategoryForm form) {
        CategoryModel model = new CategoryModel();
        BeanUtils.copyProperties(form, model);
        model.setUpdateBy(form.getUserName());

        if (model.getId() == null) {
            model.setCreateBy(form.getUserName());
            if (categoryMapper.insert(model) > 0) {
                if (model.getParentId() == null) {
                    model.setParentId(model.getId());
                    return categoryMapper.update(model) > 0;
                } else {
                    return true;
                }
            }
        } else {
            return categoryMapper.update(model) > 0;
        }
        return false;
    }

    @Override
    public boolean removeCategory(List<Long> categoryIds) {
        return categoryMapper.deleteCategory(categoryIds) > 0;
    }

    @Override
    public List<SubCategoryBean> getSubCategory(CategoryForm form) {
        CategoryModel model = new CategoryModel();
        BeanUtils.copyProperties(form, model);
        return categoryMapper.selectSubCategory(model);
    }

    @Override
    public List<CategoryModel> getParentCategory(CategoryForm form) {
        CategoryModel model = new CategoryModel();
        BeanUtils.copyProperties(form, model);
        return categoryMapper.getParentCategory(model);
    }

}
